/* eslint-disable array-bracket-spacing */
'use strict';
const path = require('path');

const sqlParser = require('sql-parser');

const Processor = require('./base_processor');
const FilterVisitor = require('./biz/filter_visitor');

const { ExcelColumns } = require('./base_processor');
const Logger = require('../lib/log/logger');
const LogUtil = require('../lib/util/log_util');
const RCMSCategoriesStore = require('./store/rcms_categories_store');

class FilterProcessor extends Processor {
  constructor(filePath) {
    super(filePath, 'FilterProcessor');
    this.logger = new Logger('FilterProcessor', LogUtil.getFileLogWriter('FilterProcessor', path.basename(this.outputFilePath)));
  }
  /**
   * 业务逻辑
   * read >> process >> write
   * @return {String} 输出文件路径
   */
  async process() {
    // 处理之前先清空日志，避免日志过多不方便查看
    this.logger.clear();

    // 用来拼接filter组成完成的select语句，否则sql_parser解析不出来
    const selectStatement = 'select * from dual where ';

    const oldDbRows = await RCMSCategoriesStore.list();

    const excelRows = this.read();
    for (const excelRow of excelRows) {
      // +2: 下标从0开始，要+1，生成excel后会多一行标题，再+1
      const rowIndex = excelRows.indexOf(excelRow) + 2;
      try {
        const filter = excelRow[ExcelColumns.FILTER];
        if (filter && filter.length > 0) {
          const oldColumnId = excelRow[ExcelColumns.OLD_COLUMN_ID];
          const oldRow = oldDbRows.find(m => m.id === oldColumnId);
          if (oldRow && oldRow.cattype === '1') {
            const filterVisitor = new FilterVisitor(excelRows);
            const parsedFilter = sqlParser.parse(`${selectStatement} ${filter}`);

            if (parsedFilter && parsedFilter.where) {
              await filterVisitor.visit(parsedFilter.where.conditions);

              excelRow[ExcelColumns.FILTER_NEW] = parsedFilter.where.toString().replace('WHERE ', 'AND ');

              const unexpected = [...filterVisitor.unexpected];
              if (unexpected && unexpected.length > 0) {
                excelRow[ExcelColumns.FILTER_NEW_REMARK] = unexpected.map(m => {
                  return `${m.filed}:${m.message}`;
                }).join(';');

                const importantUnexpected = unexpected.filter(m => m.level === 1);
                if (importantUnexpected && importantUnexpected.length > 0) {
                  this.logger.info(`(${rowIndex})` + importantUnexpected.map(m => {
                    return `${m.filed}:${m.message}`;
                  }).join(';'));
                }
              }
            } else {
              throw new Error('条件解析不成功');
            }
          }
        }
      } catch (err) {
        excelRow[ExcelColumns.FILTER_NEW] = err;
        this.logger.info(`${rowIndex}${excelRow[ExcelColumns.NEW_COLUMN]}:${excelRow[ExcelColumns.FILTER_NEW]}`);
      }
    }

    this.write(excelRows);
    return this.outputFilePath;
  }
}

module.exports = FilterProcessor;
